<template>
  <div>
    <el-upload
      :data="fileUploadInfoDto"
      :action="actionUrl"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      :before-remove="beforeRemove"
      :file-list="fileList"
      :disabled="isDisabled"
      class="upload-demo"
      name="dmsFile"
      multiple>
      <el-button v-if="!isDisabled" :disabled="isDisabled" size="small" type="primary">点击上传</el-button>
      <!-- <div v-if="!isDisabled" slot="tip" class="el-upload__tip">只能上传{{ fileType }}文件，且不超过{{ maxSize }}MB!</div>-->
      <div v-if="!isDisabled" slot="tip" class="el-upload__tip">只能上传word、pdf、图片文件，且不超过{{ maxSize }}MB!</div>
      <el-input v-show="false" :value="relation"/>
    </el-upload>
  </div>
</template>

<script>
import { queryFile, deleteById } from '@/api/basedata/file.js'
import SERVER from '@/api/server'

export default {
  components: {},
  props: { fujianStyle: String, fileType: String, fileDesc: String, maxSize: Number, billId: String, isDisabled: Boolean },

  data() {
    return {
      actionUrl: `${SERVER.DMSCLOUD_BASEDATA}/file/save/2`,
      fileList: [],
      fileUploadInfoDto: {
        billType: '',
        billId: ''
      },
      fileUploadIdStr: '',
      urlparams: {}
    }
  },
  computed: {
    relation: function() {
      if (this.billId != null && this.billId !== '' && this.billId !== undefined) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.fileUploadInfoDto.billId = this.billId
        this.listfileUploadInfoDto()
      }
      return this.billId
    }
  },

  mounted() {
    if (this.fujianStyle != null && this.fujianStyle !== '' && this.fujianStyle !== undefined) {
      this.fileUploadInfoDto.billType = this.fujianStyle
    }
  },

  methods: {
    handleAvatarSuccess(res, file, fileList) {
      this.fileUploadIdStr += ',' + res.fileUploadId
      this.$emit('getparams', this.fileUploadIdStr.slice(1), fileList.length)
    },
    beforeAvatarUpload(file) {
      if (this.fileType != null && this.fileType !== '' && this.fileType !== undefined && this.fileDesc != null && this.fileDesc !== '' && this.fileDesc !== undefined && this.fileType.indexOf(file.name.substring(file.name.lastIndexOf('.'), file.name.length)) < 0) {
        this.$message({
          type: 'error',
          message: this.fileDesc
        })
        return false
      }
      if (this.maxSize != null && this.maxSize !== '' && this.maxSize !== undefined && file.size / 1024 / 1024 > parseInt(this.maxSize)) {
        this.$message({
          type: 'error',
          message: '上传文件大小需小于' + this.maxSize + 'MB!'
        })
        return false
      }
    },
    handlePreview(file) {
      // eslint-disable-next-line no-unused-vars
      const userAgent = navigator.userAgent
      if (!!window.ActiveXObject || 'ActiveXObject' in window) {
        alert('推荐谷歌进行文件预览')
      } else {
        if (file.url === undefined || file.url === null) {
          window.open(`${SERVER.DMSCLOUD_BASEDATA}/file/billFilesDownload/` + this.fujianStyle + `/` + file.response.fileUploadId)
        } else {
          window.open(file.url) // blob格式地址
        }
      }
    },
    beforeRemove(file, fileList) {
      var id = file.key
      if (id == null || id === '') {
        id = file.response.fileUploadId
      }

      return new Promise((resolve, reject) => {
        this.$confirm('确定要删除\'' + file.name + '\'吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.deleteById(id, fileList)
          resolve(true)
        }).catch(() => {
          reject(new Error('获取数据失败'))
        })
      })
    },
    handleRemove(file, fileList) {

    },
    async deleteById(id, fileList) {
      deleteById(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功！'
        })
        this.fileUploadIdStr = this.fileUploadIdStr.replace(',' + id, '')
        this.$emit('getparams', this.fileUploadIdStr.slice(1), fileList.length)
      })
    },
    // 已上传附件列表
    async listfileUploadInfoDto() {
      queryFile(this.fujianStyle, this.billId).then(response => {
        this.fileUploadIdStr = ''
        const fileList = response.initialPreviewConfig
        const urls = response.initialPreview
        this.fileList = []
        if (fileList !== undefined && fileList.length > 0) {
          for (let i = 0; i < fileList.length; i++) {
            const obj = {}
            obj.name = fileList[i].caption
            obj.key = fileList[i].key
            obj.billType = urls[i].split('/')[3]
            obj.url = `${SERVER.DMSCLOUD_BASEDATA}` + urls[i]
            this.fileList.push(obj)
          }
        }
        this.$emit('getparams', '1', fileList.length)
      })
    }
  }
}
</script>
